import time
import psutil
import mysql.connector
import requests


todayUploadDataCount = 5



def sysResourceCheck():
    # 查询 CPU 使用率
    cpu_percent = psutil.cpu_percent(interval=1)  # 获取CPU使用率，interval参数表示采样时间间隔，这里设置为1秒
    print("当前CPU使用率：{}%".format(cpu_percent), flush = True)
    if cpu_percent < 50:
        return True
    else:
        print("非闲暇时期，暂停上传!", flush = True)
        return False
        # 退出程序或执行其他操作，例如发送报警信

    # 查询内存使用情况
    # mem = psutil.virtual_memory()
    # total_memory = mem.total  # 总内存
    # used_memory = mem.used    # 已使用内存
    # free_memory = mem.free    # 空闲内存

    # print("当前CPU使用率：{}%".format(cpu_percent))
    # print("总内存：{} bytes".format(total_memory))
    # print("已使用内存：{} bytes".format(used_memory))
    # print("空闲内存：{} bytes".format(free_memory))


def upload_data_to_server():

    # 这里是你要执行的任务代码
    print("上传数据到云端库--任务执行中...", flush = True)


    sql = "SELECT config_value FROM dynamic_config WHERE config_name = %s"
    cursor.execute(sql, ('upload_sign_serial',))
    result = cursor.fetchone()
    if result is None:
        print("未查询到动态配置项，需进行初始化配置...", flush = True)
        return
    else:
        serial = result[0]
        print("已传输数据的卷号 serial:", serial, flush = True)

        # 定义接口 URL
        uploadDataUrl = "http://139.129.16.125:8602/dataUpload/tongbo"
        sql = "SELECT config_value FROM dynamic_config WHERE config_name = %s"
        cursor.execute(sql, ('upload_url',))
        result = cursor.fetchone()
        if result is None:
            print("未查询到动态配置项，使用默认url", flush = True)
        else:
            uploadDataUrl = result[0]
        print("uploadDataUrl:",uploadDataUrl, flush = True)

        

        sql = "SELECT config_value FROM dynamic_config WHERE config_name= %s"
        cursor.execute(sql, ('upload_sign_flaw_id',))
        result = cursor.fetchone()
        flaw_id = result[0]
        print("已传输数据的缺陷id flaw_id:", flaw_id, flush = True)

        sql = "SELECT id FROM flaw WHERE cloth_serial= %s order by id desc limit 1"
        cursor.execute(sql, (serial,))
        result = cursor.fetchone()
        max_flaw_id = 0
        if result is None:
            print("未查询到缺陷id，本卷暂无缺陷数据...", flush = True)
        else:
            max_flaw_id = result[0]
        print("当前卷的最大缺陷id max_flaw_id:", max_flaw_id, flush = True)

        if(int(max_flaw_id) == int(flaw_id)):
            # 查询是否出现下一卷
            sql = "SELECT id,end_time FROM clothinfo WHERE cloth_serial= %s"
            cursor.execute(sql, (serial,))
            result = cursor.fetchone()
            if result is None:
                print("未查询到下一卷，等待后续数据...", flush = True)
                return


            print('clothinfo:', result, flush = True)
            clothId = result[0]
            endTime = result[1]

            if endTime is None:
                print("虽然已上传本卷所有数据,但本卷未检测完结,等待检测数据更新，后续继续上传...", flush = True)
                return
            else:
                print("本卷已结束...", flush = True)

                sql = "SELECT cloth_serial FROM clothinfo WHERE id > %s limit 1"
                cursor.execute(sql, (clothId,))
                result = cursor.fetchone()
                if result is None:
                    print("没有查询到下一卷，等待后续数据...", flush = True)

                clothSerial = result[0]
                print("已出现新卷，更新下一卷需要上传的卷号:",clothSerial, flush = True)
            
                sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                cursor.execute(sql, (clothSerial, 'upload_sign_serial'))
                conn.commit()

                sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                cursor.execute(sql, (0, 'upload_sign_flaw_id'))
                conn.commit()

                print("将新数据卷{}的概况信息上传到云端...".format(clothSerial), flush = True)
                sql = "SELECT cloth_serial,bar_code,cloth_width,cloth_weight,cloth_long,total_counts,groupteam,operator,DATE_FORMAT(`timestamp`, %s),DATE_FORMAT(`begin_time`, %s),DATE_FORMAT(`end_time`, %s),remark FROM clothinfo WHERE cloth_serial = %s"
                cursor.execute(sql, ('%Y-%m-%d %H:%i:%s' ,'%Y-%m-%d %H:%i:%s' ,'%Y-%m-%d %H:%i:%s' ,clothSerial,))
                result = cursor.fetchone()
                clothInfo = {
                    "clothSerial": result[0],
                    "barCode": result[1],
                    "clothWidth": result[2],
                    "clothWeight": result[3],
                    "clothLong": result[4],
                    "totalCounts": result[5],
                    "groupteam": result[6],
                    "operator": result[7],
                    "timestamp": result[8],
                    "beginTime": result[9],
                    "endTime": result[10],
                    "remark": result[11]
                }

                clothData = {
                    "type": "cloth",
                    "clothinfo": clothInfo
                }
                response = requests.post(uploadDataUrl, json=clothData)
                print("上传结果：", response.text, flush = True)

        elif(int(max_flaw_id) > int(flaw_id)):
            print("当前卷数据未全部上传，继续上传...", flush = True)


            sql = "SELECT cloth_serial,bar_code,cloth_width,cloth_weight,cloth_long,total_counts,groupteam,operator,DATE_FORMAT(`timestamp`, %s),DATE_FORMAT(`begin_time`, %s),DATE_FORMAT(`end_time`, %s),remark FROM clothinfo WHERE cloth_serial = %s"
            cursor.execute(sql, ('%Y-%m-%d %H:%i:%s' ,'%Y-%m-%d %H:%i:%s' ,'%Y-%m-%d %H:%i:%s' ,serial,))
            result = cursor.fetchone()
            if result is None:
                print("卷info异常...暂停数据上传", flush = True)
                return
            else:

                clothInfo = {
                    "clothSerial": result[0],
                    "barCode": result[1],
                    "clothWidth": result[2],
                    "clothWeight": result[3],
                    "clothLong": result[4],
                    "totalCounts": result[5],
                    "groupteam": result[6],
                    "operator": result[7],
                    "timestamp": result[8],
                    "beginTime": result[9],
                    "endTime": result[10],
                    "remark": result[11]
                }

                clothData = {
                    "type": "cloth",
                    "clothinfo": clothInfo
                }
                response = requests.post(uploadDataUrl, json=clothData)
                print("clothinfo上传结果：", response.text, flush = True)
            limit = 100
            sql = "SELECT config_value FROM dynamic_config WHERE config_name = %s"
            cursor.execute(sql, ('upload_limit',))
            result = cursor.fetchone()
            if result is None:
                print("未查询到动态配置项，使用默认limit", flush = True)
            else:
                limit = result[0]


            sql = "SELECT id,cloth_serial,camera_id,class_str,real_len,real_area,real_pos_x,real_pos_y,pnt,img_data,DATE_FORMAT(`timestamp`, %s) FROM flaw WHERE img_data like '%/9j/%' and cloth_serial= %s and id > %s limit %s"
            cursor.execute(sql, ('%Y-%m-%d %H:%i:%s' ,serial, flaw_id, int(limit),))
            result = cursor.fetchall()

            # 调用云端HTTP接口上传数据
            # 定义要上传的 JSON 数据
            flaws = []
            end_id = 0
            for row in result:
                flaw = {
                    "clothSerial": row[1],
                    "cameraId": row[2],
                    "classStr": row[3],
                    "realLen": row[4],
                    "realArea": row[5],
                    "realPosX": row[6],
                    "realPosY": row[7],
                    "pnt": row[8],
                    "imgData": row[9],
                    "timestampNew": row[10]
                }
                flaws.append(flaw)
                end_id = row[0]

            # print(flaws)
            print("end_id:", end_id, flush = True)

            flawsData = {
                "type": "flaw",
                "flaws": flaws
            }

            

            # 发送 POST 请求并携带 JSON 数据
            response = requests.post(uploadDataUrl, json=flawsData)

            print("上传结果：", response.text, flush = True)
            if(response.text.find('"code":200')):
                print("上传成功,已上传数据id:", end_id, flush = True)

                if(end_id == max_flaw_id):
                    sql = "SELECT id,end_time FROM clothinfo WHERE cloth_serial= %s"
                    cursor.execute(sql, (serial,))
                    result = cursor.fetchone()
                    clothId = result[0]
                    endTime = result[1]

                    if endTime is None:
                        print("虽然已上传本卷当前所有数据,但本卷未检测完结,更新upload_sign_flaw_id,等待后续继续上传...", flush = True)
                        sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                        cursor.execute(sql, (end_id, 'upload_sign_flaw_id'))
                        conn.commit()
                        return
                    else:
                        print("当前卷已结束且数据上传完成，变更动态配置项...", flush = True)
                        sql = "SELECT cloth_serial FROM clothinfo WHERE id > %s limit 1"
                        cursor.execute(sql, (clothId,))
                        result = cursor.fetchone()
                        if(result is None):
                            print("已上传完所有卷，暂不需要更新upload_sign_serial", flush = True)
                            sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                            cursor.execute(sql, (end_id, 'upload_sign_flaw_id'))
                            conn.commit()
                            return 
                        else:
                            clothSerial = result[0]
                            print("更新下一卷需要上传的卷号:",clothSerial, flush = True)
                        
                            sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                            cursor.execute(sql, (clothSerial, 'upload_sign_serial'))
                            conn.commit()

                            sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                            cursor.execute(sql, (0, 'upload_sign_flaw_id'))
                            conn.commit()

                            print("将新数据卷{}的概况信息上传到云端...".format(clothSerial), flush = True)
                            sql = "SELECT cloth_serial,bar_code,cloth_width,cloth_weight,cloth_long,total_counts,groupteam,operator,DATE_FORMAT(`timestamp`, %s),DATE_FORMAT(`begin_time`, %s),DATE_FORMAT(`end_time`, %s),remark FROM clothinfo WHERE cloth_serial = %s"
                            cursor.execute(sql, ('%Y-%m-%d %H:%i:%s' ,'%Y-%m-%d %H:%i:%s' ,'%Y-%m-%d %H:%i:%s' ,clothSerial,))
                            result = cursor.fetchone()
                            clothInfo = {
                                "clothSerial": result[0],
                                "barCode": result[1],
                                "clothWidth": result[2],
                                "clothWeight": result[3],
                                "clothLong": result[4],
                                "totalCounts": result[5],
                                "groupteam": result[6],
                                "operator": result[7],
                                "timestamp": result[8],
                                "beginTime": result[9],
                                "endTime": result[10],
                                "remark": result[11]
                            }

                            clothData = {
                                "type": "cloth",
                                "clothinfo": clothInfo
                            }
                            response = requests.post(uploadDataUrl, json=clothData)
                            print("上传结果：", response.text, flush = True)

                else:
                    print("本卷数据未上传完成,更新upload_sign_flaw_id,等待继续上传...", flush = True)
                    sql = "UPDATE dynamic_config SET config_value = %s WHERE config_name = %s"
                    cursor.execute(sql, (end_id, 'upload_sign_flaw_id'))
                    conn.commit()
                    return
        
        else:
            print("配置项异常{}__{}__{}".format(serial, flaw_id, result[0]), flush = True)







print("铜箔数据上传程序启动...定时任务会在每日某个时间段执行")
while True:
    # 获取当前计算机时间
    print("====================================>>>", flush = True)
    print("当前时间：", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), flush = True)
    current_time = time.strftime("%H", time.localtime())

    # conn = mysql.connector.connect(host='localhost', user='root', password='root', port=3306, charset='utf8', database='idetect')
    conn = mysql.connector.connect(host='localhost', user='root', password='jmai4nd@9xT', port=3306, charset='utf8', database='idetect')
    cursor = conn.cursor()

    timeStr = '02,03,04'
    sql = "SELECT config_value FROM dynamic_config WHERE config_name = %s"
    cursor.execute(sql, ('upload_time',))
    result = cursor.fetchone()
    if result is None:
        print("未查询到动态配置项，使用默认timeStr", flush = True)
    else:
        timeStr = result[0]
    
    # current_time == "02" or current_time == "03" or current_time == "04"
    if (timeStr.find(current_time) != -1):
        if sysResourceCheck():
            print("资源检查通过，开始执行任务...", flush = True)
            try:
                # 调用特定方法，可能会抛出异常
                upload_data_to_server()
            except Exception as e:
                # 处理任何可能抛出的异常
                print("捕获到异常:", e)
            else:
                # 如果没有发生异常，执行此代码块
                print("数据上传任务执行成功:")

            
        else:
            print("资源检查不通过，任务取消...", flush = True)
    time.sleep(30)  # 每隔30s检查一次，可以根据需要调整间隔时间

